package com.lantosec.hmrp.core.util.identify;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.net.URLEncoder;

//身份证识别
public class Idcard {
    public static IdCardBean idcard(String type,String filePath) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
        try {
            // 本地文件路径
            //String filePath = "";
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            //身份证正面传front，背面传back
            String param = "id_card_side=" + type + "&image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = AuthService.getAuth();

            String result = HttpUtil.post(url, accessToken, param);

            //封装成对象
            IdCardBean bean = new IdCardBean();
            JSONObject jsonObject = JSON.parseObject(result);
            //身份证正面信息
            if("front".equals(type)){
                String name =  jsonObject.getJSONObject("words_result").getJSONObject("姓名").getString("words");
                String address =  jsonObject.getJSONObject("words_result").getJSONObject("住址").getString("words");
                String bitrh =  jsonObject.getJSONObject("words_result").getJSONObject("出生").getString("words");
                String idCardNum =  jsonObject.getJSONObject("words_result").getJSONObject("公民身份号码").getString("words");
                String sex =  jsonObject.getJSONObject("words_result").getJSONObject("性别").getString("words");
                String ethnic =  jsonObject.getJSONObject("words_result").getJSONObject("民族").getString("words");
                bean.setName(name);
                bean.setAddress(address);
                bean.setBirth(bitrh);
                bean.setIdCardNum(idCardNum);
                bean.setSex(sex);
                bean.setEthnic(ethnic);
            }else{
                //身份证反面信息
                String expiryDate =  jsonObject.getJSONObject("words_result").getJSONObject("失效日期").getString("words");
                String issuingAuthority =  jsonObject.getJSONObject("words_result").getJSONObject("签发机关").getString("words");
                String issueDate =  jsonObject.getJSONObject("words_result").getJSONObject("签发日期").getString("words");
                bean.setExpiryDate(expiryDate);
                bean.setIssuingAuthority(issuingAuthority);
                bean.setIssueDate(issueDate);
            }

            System.out.println(result);
            return bean;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*public static void main(String[] args) {
        Idcard.idcard("back");
    }*/
}
